package com.ld.curator.api;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @author:ld
 * @create:2020-04-24 11:16
 * @description: Curator框架 判断节点是否存在
 */
public class CuratorExists {


    //客户端对象
    private CuratorFramework client;
    //连接地址
    private final String IP = "127.0.0.1:2181";

    /**
     * 获取连接
     */
    @Before
    public void before(){
        //重试机制，即每隔1秒，重试一次，一共可以重试3次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        //方式一：获取客户端对象
//        client = CuratorFrameworkFactory.newClient(IP, 5000, 3000, retryPolicy);
        //方式二：获取客户端对象
        client = CuratorFrameworkFactory
                .builder()
                .connectString(IP)//连接地址
                .connectionTimeoutMs(3000) //连接超时时间
                .sessionTimeoutMs(5000) //会话超时时间
                .retryPolicy(retryPolicy) //重试机制
                .namespace("base") //命名空间，即指定根节点，后续操作都在根节点下。注意：开头不要加 “/”
                .build();


        //开启连接
        client.start();
    }

    /**
     * 关闭连接
     */
    @After
    public void close(){
        client.close();
    }

    @Test
    public void exists1() throws Exception {
        Stat stat = client.checkExists().forPath("/exists");
        if(stat == null){
            System.out.println("节点不存在......");
        }else
        System.out.println(stat.getVersion());
    }

}
